<template>
  <div class="data-input">
    <el-card class="input-card">
      <div slot="header">
        <span>数据录入</span>
      </div>

      <el-form
        :model="formData"
        :rules="rules"
        ref="form"
        label-position="top"
        label-width="100px"
      >
        <!-- 问题名称 -->
        <el-form-item label="问题名称" prop="problem">
          <el-input
            v-model="formData.problem"
            type="textarea"
            :rows="2"
            placeholder="请输入问题名称"
          ></el-input>
        </el-form-item>

        <!-- 问题描述 -->
        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入问题描述"
          ></el-input>
        </el-form-item>

        <!-- 步骤 -->
        <el-divider content-position="left">解决步骤</el-divider>
        <div v-for="(step, index) in formData.steps" :key="index" class="step-container">
          <el-card class="step-card">
            <div slot="header" class="step-header">
              <span>步骤 {{ index + 1 }}</span>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeStep(index)"
              >
                删除步骤
              </el-button>
            </div>

            <!-- 步骤标题 -->
            <el-form-item
              :prop="`steps[${index}].title`"
              :rules="rules.stepTitle"
              label="步骤标题"
            >
              <el-input v-model="step.title" placeholder="请输入步骤标题"></el-input>
            </el-form-item>

            <!-- 步骤详情 -->
            <el-form-item label="步骤详情">
              <el-input
                v-model="step.details"
                type="textarea"
                :rows="3"
                placeholder="请输入步骤详情"
              ></el-input>
            </el-form-item>

            <!-- 操作角色 -->
            <el-form-item
              :prop="`steps[${index}].role`"
              :rules="rules.stepRole"
              label="操作角色"
            >
              <el-select v-model="step.role" placeholder="请选择操作角色">
                <el-option label="技术支持" value="技术支持"></el-option>
                <el-option label="作业人员" value="作业人员"></el-option>
              </el-select>
            </el-form-item>

            <!-- 操作 -->
            <el-divider content-position="left">操作</el-divider>
            <div v-for="(action, actionIndex) in step.actions" :key="actionIndex" class="action-item">
              <el-card class="action-card" v-if="action.visible">
                <div slot="header" class="action-header">
                  <span>操作 {{ actionIndex }}</span>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeAction(step, actionIndex)"
                  ></el-button>
                </div>
                <!-- 操作详情 -->
                 <el-form-item label="操作详情">
                  <el-input
                    v-model="action.detail"
                    type="input"
                    :rows="3"
                    placeholder="请输入操作详情"
                  ></el-input>
                 </el-form-item>
                <!-- 操作类型 -->
                <el-form-item label="操作类型">
                  <el-select v-model="action.action" placeholder="选择操作类型" class="action-select">
                    <el-option label="SQL语句" value="sql"></el-option>
                    <el-option label="路径操作" value="path"></el-option>
                    <el-option label="代码操作" value="code"></el-option>
                  </el-select>
                </el-form-item>

                <!-- 操作内容 -->
                <el-form-item :label="actionLabel(action.action)">
                  <el-input
                    v-model="action[action.action]"
                    type="textarea"
                    :rows="3"
                    :placeholder="`请输入${actionLabel(action.action)}`"
                  ></el-input>
                </el-form-item>
              </el-card>
            </div>

            <!-- 添加操作按钮 -->
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addAction(step)"
            >
              添加操作
            </el-button>
          </el-card>
        </div>

        <!-- 添加步骤按钮 -->
        <div class="step-actions">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addStep"
          >
            添加步骤
          </el-button>
        </div>

        <!-- 附加说明 -->
        <el-divider content-position="left">附加说明</el-divider>
        <div class="notes-container">
          <div v-for="(note, index) in formData.additional_notes" :key="index" class="note-item">
            <el-input
              v-model="formData.additional_notes[index]"
              type="textarea"
              :rows="2"
              placeholder="请输入附加说明"
            >
              <template slot="append">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeNote(index)"
                ></el-button>
              </template>
            </el-input>
          </div>

          <!-- 添加说明按钮 -->
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addNote"
          >
            添加说明
          </el-button>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 确认信息弹窗 -->
    <el-dialog
      title="确认提交信息"
      :visible.sync="confirmDialogVisible"
      width="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="问题名称">{{ formData.problem }}</el-descriptions-item>
        <el-descriptions-item label="问题描述">{{ formData.description }}</el-descriptions-item>
        <el-descriptions-item label="步骤">
          <div v-for="(step, index) in formData.steps" :key="index">
            <p>步骤 {{ index + 1 }}: {{ step.title }}</p>
            <p>详情: {{ step.details }}</p>
            <p>角色: {{ step.role }}</p>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="附加说明">
          <div v-for="(note, index) in formData.additional_notes" :key="index">
            <p>说明 {{ index + 1 }}: {{ note }}</p>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmSubmit">确认提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DataInput',
  data() {
    return {
      formData: {
        problem: '',
        description: '',
        steps: [
          {
            title: '',
            details: '',
            role: '',
            actions: [
              {
                action: 'sql',
                sql: '',
                visible: false, // 默认隐藏操作窗口
              },
            ],
          },
        ],
        additional_notes: [''],
      },
      rules: {
        problem: [
          { required: true, message: '请输入问题名称', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入问题描述', trigger: 'blur' },
        ],
        stepTitle: [
          { required: true, message: '请输入步骤标题', trigger: 'blur' },
        ],
        stepRole: [
          { required: true, message: '请选择操作角色', trigger: 'change' },
        ],
      },
      confirmDialogVisible: false, // 确认弹窗显示状态
    };
  },
  methods: {
    // 操作类型标签
    actionLabel(action) {
      const labels = {
        sql: 'SQL语句',
        path: '操作路径',
        code: '代码内容',
      };
      return labels[action] || '内容';
    },

    // 添加步骤
    addStep() {
      this.formData.steps.push({
        title: '',
        details: '',
        role: '',
        actions: [
          {
            action: 'sql',
            sql: '',
            visible: false, // 默认隐藏操作窗口
          },
        ],
      });
    },

    // 删除步骤
    removeStep(index) {
      this.$confirm('确认删除该步骤?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.formData.steps.splice(index, 1);
      });
    },

    // 添加操作
    addAction(step) {
      step.actions.push({
        detail:'',
        action: 'sql',
        sql: '',
        visible: true, // 新增时显示操作窗口
      });
    },

    // 删除操作
    removeAction(step, actionIndex) {
      step.actions.splice(actionIndex, 1);
    },

    // 添加说明
    addNote() {
      this.formData.additional_notes.push('');
    },

    // 删除说明
    removeNote(index) {
      this.formData.additional_notes.splice(index, 1);
    },

    // 提交表单
    async submitForm() {
      try {
        // 表单校验
        await this.$refs.form.validate();

        // 过滤掉 visible 为 false 的操作
        const filteredSteps = this.formData.steps.map(step => {
          return {
            ...step,
            actions: step.actions.filter(action => action.visible), // 只保留 visible 为 true 的操作
          };
        });

        // 更新 formData.steps
        this.formData.steps = filteredSteps;

        // 显示确认弹窗
        this.confirmDialogVisible = true;
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.warning('请填写所有必填项');
        }
      }
    },

    // 确认提交
    async handleConfirmSubmit() {
      try {
        // 提交数据
        const response = await this.$request.post('/tpa/api/save_data/', this.formData);
        if (response.status === 'success') {
          this.$message.success('保存成功');
          this.resetForm();
          this.confirmDialogVisible = false;
        }
      } catch (error) {
        this.$message.error('提交失败，请稍后重试');
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        problem: '',
        description: '',
        steps: [
          {
            title: '',
            details: '',
            role: '',
            actions: [
              {
                action: 'sql',
                sql: '',
                visible: false, // 默认隐藏操作窗口
              },
            ],
          },
        ],
        additional_notes: [''],
      };
      this.$refs.form.clearValidate(); // 清除校验状态
    },
  },
};
</script>

<style scoped>
.data-input {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.input-card {
  margin-bottom: 20px;
}

.step-container {
  margin-bottom: 20px;
}

.step-card {
  margin-bottom: 15px;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-card {
  margin-bottom: 15px;
}

.action-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-select {
  width: 100%;
}

.note-item {
  margin-bottom: 15px;
}

.form-actions {
  margin-top: 20px;
  text-align: center;
}
</style>